// pages/search/calories/calories.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    keyword: "",
    results: [],
    items: [],
    searchOptions: ["推荐搜索", "热量搜索"],
    selectedSearchOption: "热量搜索",
    page: 1,
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.setData({
      page: this.data.page + 1,
    });
    this.fetchData();
  },
  onLoad(options) {
    this.setData({
      keyword: options.term || "", // 获取传递的搜索关键词
    });
    if (options.term) {
      this.handleSearch()
    }
  },

  onSearchInput(e) {
    this.setData({
      keyword: e.detail.value,
    });
  },

  handleSearch() {
    this.setData({
      page: 1,
      items: []
    });
    this.fetchData();
  },

  fetchData() {
    const {
      keyword,
      page
    } = this.data;
    if (!keyword) {
      wx.showToast({
        title: "请输入关键词",
        icon: "none",
      });
      return;
    }

    const url = "https://www.boohee.com/food/search";
    this.fetchHtml(url, keyword, page);
  },

  fetchHtml(url, keyword, page) {
    wx.request({
      url: url,
      method: "GET",
      data: {
        keyword,
        page
      },
      header: {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
      },
      success: (res) => {
        console.log("结果", res);
        if (res.statusCode === 200) {
          const htmlContent = res.data;
          this.parseHtml(htmlContent);
        } else {
          wx.showToast({
            title: "请求失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        console.error("请求发生异常:", err);
        wx.showToast({
          title: "请求异常",
          icon: "none",
        });
      },
    });
  },

  parseHtml(htmlContent) {
    const results = [];
    const itemRegex = /<li class="item clearfix">([\s\S]*?)<\/li>/g;
    let itemMatch;

    while ((itemMatch = itemRegex.exec(htmlContent)) !== null) {
      const itemHtml = itemMatch[1];

      const imageRegex = /<div class="img-box pull-left">([\s\S]*?)<\/div>/;
      const textRegex = /<div class="text-box pull-left">([\s\S]*?)<\/div>/;

      const imageMatch = imageRegex.exec(itemHtml);
      const textMatch = textRegex.exec(itemHtml);

      const imageHtml = imageMatch ? imageMatch[1] : "";
      const textHtml = textMatch ? textMatch[1] : "";

      const imageSrcMatch = /<img[^>]+src=['"]([^'"]+)['"]/.exec(imageHtml);
      const nameMatch = /<a[^>]*>(.*?)<\/a>/.exec(textHtml);
      const calorieMatch = /<p>热量：(\d+) 大卡/.exec(textHtml);

      const image = imageSrcMatch ?
        imageSrcMatch[1] :
        "https://s.boohee.cn/house/upload_food/2021/7/23/small_photo_url_09.png"; // 默认图片
      const name = nameMatch ? nameMatch[1].trim() : "未知食物";
      const calorie = calorieMatch ? parseInt(calorieMatch[1]) : 0;

      results.push({
        id: results.length + 1,
        image,
        name,
        description: name,
        calories: calorie,
      });
    }

    this.setData({
      items: this.data.items.concat(results),
    });
  },

  // 处理搜索输入
  handleInput(e) {
    const inputValue = e.detail.value;
    this.setData({
      keyword: inputValue,
    });
  },

  toggleSearchOption() {
    const currentIndex = this.data.searchOptions.indexOf(
      this.data.selectedSearchOption
    );
    const nextIndex = (currentIndex + 1) % this.data.searchOptions.length;
    const nextOption = this.data.searchOptions[nextIndex];
    this.setData({
      selectedSearchOption: nextOption,
    });
    // 在这里可以根据选择的搜索选项执行相应的逻辑
  },
});